package com.gzcc.controller;


import com.gzcc.model.Brand;
import com.gzcc.model.Category;
import com.gzcc.model.Product;
import com.gzcc.repository.BrandRepository;
import com.gzcc.repository.CategoryRepository;
import com.gzcc.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * 描述: 商品controller
 *
 * @Author: Mr.Zhong
 * @Date: 2018/6/13
 */
@Controller
@RequestMapping("/shop")
public class ProductController {

    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private BrandRepository brandRepository;
    @Autowired
    private CategoryRepository categoryRepository;


    @Value("ckeditor.storage.image.path")
    private String path;

    @Value("${imagefile.path}")
    private String imagepath;

    /**
     * 描述: 跳转商品列表
     *
     * @Author: Mr.Zhong
     * @Date: 2018/6/13
     */
    @RequestMapping()
    public ModelAndView shopList() {
        ModelAndView mv = new ModelAndView();
        List<Product> products = productRepository.findAll();
        mv.addObject("products", products);
        mv.setViewName("backend/product/product_list.btl");
        return mv;
    }

    /**
     * 描述:
     *
     * @Author: Mr.Zhong
     * @Date: 2018/6/13
     */
    @RequestMapping("/detail")
    public ModelAndView shopDetail() {
        ModelAndView mv = new ModelAndView();
        List<Brand> brandList = brandRepository.findAll();
        List<Category> categoryList = categoryRepository.findAll();
        mv.addObject("brandList", brandList);
        mv.addObject("categoryList", categoryList);
        mv.setViewName("backend/product/product_detail.btl");
        return mv;
    }

    /**
     * 描述: 添加商品
     *
     * @param product
     * @return
     * @Author: Mr.Zhong
     * @Date: 2018/6/13
     */
    @RequestMapping(value = "form", method = RequestMethod.POST)
    public String productInput(@ModelAttribute Product product, @RequestParam(value = "name") String name, @RequestParam(value = "checkbox") String[] color, @RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
//        try {
//            if (file.isEmpty()) {
//                return "文件为空";
//            }
//            // 获取文件名
//            String fileName = file.getOriginalFilename();
//            // 获取文件的后缀名
//            String suffixName = fileName.substring(fileName.lastIndexOf("."));
//            // 设置文件存储路径
//            String filePath = "D:/aim/";
//            String path = filePath + fileName + suffixName;
//            product.setPicture(path);
//            File dest = new File(path);
//            // 检测是否存在目录
//            if (!dest.getParentFile().exists()) {
//                dest.getParentFile().mkdirs();// 新建文件夹
//            }
//            file.transferTo(dest);// 文件写入
        // Product product=new Product();
        if (!file.isEmpty()) {
            UUID img=UUID.randomUUID();
            try {
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(path + img + ".jpg")));//保存图片到目录下
                out.write(file.getBytes());
                out.flush();
                out.close();
                String filename =imagepath+ img + ".jpg";
                //user.setTupian(filename);
                product.setPicture(filename);
                String[] CorpMode = color;
                String SCorpMode = "";
                if (CorpMode.length > 0) {
                    for (int i = 0; i < CorpMode.length; i++) {
                        SCorpMode = SCorpMode + CorpMode[i] + ",";
                    }
                    SCorpMode = SCorpMode.substring(0, SCorpMode.length() - 1);
                    product.setColor(SCorpMode);
                }
                //product.setColor(color);
                productRepository.save(product);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }
            return "redirect:/shop";
        } else {
            return "上传失败，因为文件是空的.";
        }


    }

    /**
     * 描述: 编辑商品页面
     *
     * @param id
     * @return
     * @Author: Mr.Zhong
     * @Date: 2018/6/13
     */
    @RequestMapping(value = "/toEdit", method = RequestMethod.GET)
    public ModelAndView edit(@RequestParam("id") int id) {


        ModelAndView mv = new ModelAndView();
        Product product = productRepository.findById(id).get();
        String s = product.getColor();
        List<Brand> brandList = brandRepository.findAll();
        List<Category> categoryList = categoryRepository.findAll();
        mv.addObject("categoryList", categoryList);
        mv.addObject("brandList", brandList);
        mv.addObject("product", product);
        mv.setViewName("backend/product/toEdit.btl");
        return mv;
    }

    /**
     * 描述: 修改商品
     *
     * @param
     * @return
     * @Author: Mr.Zhong
     * @Date: 2018/6/13
     */
    @RequestMapping(value = "edit", method = RequestMethod.GET)
    public Product productUpdate(@PathVariable("id") long id,
                                 @RequestParam("name") String name,
                                 @RequestParam("age") Integer age) {
        Product product = new Product();
        product.setId(id);
        product.setName(name);
        return productRepository.save(product);
    }

    /**
     * 描述: 删除商品
     *
     * @param
     * @return
     * @Author: Mr.Zhong
     * @Date: 2018/6/13
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(@RequestParam("id") long id) {
        productRepository.deleteById((int) id);
        return "redirect:/shop";
    }

    /**
     * 描述: 查询商品
     *
     * @param
     * @return
     * @Author: Mr.Zhong
     * @Date: 2018/6/13
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView search(@RequestParam("name") String name) {
        List<Product> products = productRepository.findAllByBrandNameLike(name);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("products", products);
        modelAndView.setViewName("backend/product/product_search_list.btl");
        return modelAndView;

    }

//    @RequestMapping(value = "/upload/image",method = RequestMethod.POST)
//    @ResponseBody
//    public String uploadImage(@RequestParam("comments") String comments, @RequestParam("upload") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
//        String name = "";
//        //Logger logger = org.apache.log4j.Logger.getLogger(FilesController.class);
//        if (!file.isEmpty()) {
//            try {
//                response.setContentType("text/html; charset=UTF-8");
//                response.setHeader("Cache-Control", "no-cache");
//
//                //解决跨域问题
//                //Refused to display 'http://localhost:8080/upload/mgmt/img?CKEditor=practice_content&CKEditorFuncNum=1&langCode=zh-cn' in a frame because it set 'X-Frame-Options' to 'DENY'.
//                response.setHeader("X-Frame-Options", "SAMEORIGIN");
//                PrintWriter out = response.getWriter();
//
//                String fileClientName = file.getOriginalFilename();
////                String ckeditorStorageImagePath="D:\\data\\file\\image\\images\\";
////                String pathName = ckeditorStorageImagePath + fileClientName;
////                File newfile = new File(pathName);
////
//                String ckeditorStorageImagePath="D:\\data\\file\\image\\images\\";
//                String rootFilePath=ckeditorStorageImagePath+"\\images\\";
//                File rootFile=new File(rootFilePath);
//                if (!rootFile.exists()){
//                    rootFile.mkdir();
//                }
//                String pathName = rootFile +File.separator+ fileClientName;
//                File newfile = new File(pathName);
//
//                byte[] bytes = file.getBytes();
//                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(newfile));
//                stream.write(bytes);
//                stream.close();
//                String ckeditorAccessImageUrl="http://localhost:8090";
//
//                // 组装返回url，以便于ckeditor定位图片
//                String fileUrl = ckeditorAccessImageUrl +"/public/image/images"+ File.separator + newfile.getName();
//
//                // 将上传的图片的url返回给ckeditor
//                String callback = request.getParameter("CKEditorFuncNum");
//                String script = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + callback + ", '" + fileUrl + "');</script>";
//
//                out.println(script);
//                out.flush();
//                out.close();
//
//                test test1=new test();
//                test1.setId(1);
//                test1.setContent(comments);
//
//                testRepository.save(test1);
//            } catch (Exception e) {
//               logger  ("You failed to upload " + name + " => " + e.getMessage());
//            }
//        } else {
//            logger ("You failed to upload " + name + " because the file was empty.");
//        }
//
//        return "SUCCESS";
//    }


}

